package ThreadPool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 手动实现线程池
 */
class MyThreadPool {
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    public void submit(Runnable task) throws InterruptedException {
        queue.put(task);
    }

    public MyThreadPool(int n) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
               try {
                   while (true) {
                       Runnable runnable = queue.take();
                       runnable.run();
                   }
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
            });
            t.setDaemon(true);
            t.start();
        }
    }
}

public class demo2 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(4);
        for (int i = 0; i < 1000; i++) {
            int id = i;
            pool.submit(() -> {
                System.out.println("hello " + Thread.currentThread().getName() + " " + id);
            });
        }
        Thread.sleep(1000);
    }
}
